package com.example.data_save;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

public class SharedPreferencesDemo extends AppCompatActivity implements View.OnClickListener {

    private EditText etName;
    private EditText etAge;
    private SharedPreferences preferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shared_preferences_demo);
        etName = findViewById(R.id.et_name);
        etAge = findViewById(R.id.et_age);
        findViewById(R.id.btn_saveData).setOnClickListener(this);

        //保存数据
        preferences = getSharedPreferences("config", Context.MODE_PRIVATE);

        //读取共享数据
        String name = preferences.getString("name",null);
        Integer age = preferences.getInt("age",0);
        if(name!=null){
            etName.setText(name);
        }
        if(age!=0){
            etAge.setText(String.valueOf(age));
        }
    }

    @Override
    public void onClick(View view) {
        String name = etName.getText().toString();
        String age = etAge.getText().toString();

        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("name",name);
        editor.putInt("age",Integer.parseInt(age));
        editor.commit();
    }
}